import axios from 'axios';
import router from '../../router';
import qs from 'qs';

import { localStorage } from './storage'
import store from "@/vuex/store"
import { Message } from 'element-ui'

let baseURL = 'http://swoole_api.shuzi88.com';
let request = axios.create({
  baseURL,
  timeout: 10000,
  headers: {
    "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
  }
})

request.interceptors.request.use(config => {
  let token = localStorage.getItem('token');
  // 2. 带上token
  if (token) {
    config.headers.token = token;
  }else {
    router.push('/login')
  }
  if(config.method === 'post'){
    config.data = qs.stringify(config.data);
  }

  return config
}, error => {
  return Promise.reject(error)
})

request.interceptors.response.use(data => {
  if(data.data.msg === 'token过期'){
    store.commit('TOKEN', '');
    window.location.href = window.location.origin + '/#/login'
  }
  // console.log(data)
  // if (data.data.code == 201 || data.data.code == 110 || data.data.code == 1011 ) {
  //   Message({
  //     message: '登录失效，请重新登录',
  //     center: true,
  //     type: 'error',
  //     duration: 1000,
  //     onClose: () => {
  //       store.dispatch('setUserInfo', null)
  //       window.location.href = window.location.origin + '/#/login'
  //     }
  //   })
  // } else if (+data.data.status !== 200) {
  //   Message({
  //     message: data.data.msg,
  //     center: true,
  //     type: 'error'
  //   })
  // }
  return data
}, error => {
  return Promise.reject(error)
})

export default {
  post (url, data) {
    return request.post(url, data)
  },
  put (url, data) {
    return request.put(url, data)
  },
  delete (url, data) {
    return request.delete(url, {
      params: data
    })
  },
  get (url, data) {
    return request.get(url, {
      params: data
    })
  }
}